package com.erebus.login.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.erebus.base.model.RestResponse;
import com.erebus.login.mapper.StudentMapper;
import com.erebus.login.mapper.TeacherMapper;
import com.erebus.login.model.dto.AuthParamsDto;
import com.erebus.login.model.dto.UserExt;
import com.erebus.login.model.po.Student;
import com.erebus.login.model.po.Teacher;
import com.erebus.login.service.AuthService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class UserServiceImpl implements UserDetailsService {

    @Autowired
    ApplicationContext applicationContext;


    // 传入的参数是AuthParamsDto
    // 用户不存在返回null给security框架
    // 如果查到用户，拿到正确密码，封装成UserDetails对象给security框架返回，由框架进行密码比对
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {

        // 将json转成AuthParamsDto
        AuthParamsDto authParamsDto = null;
        authParamsDto = JSON.parseObject(s, AuthParamsDto.class);

        // 认证类型(暂时只有账号密码认证)
        //String authType = authParamsDto.getAuthType();
        // 根据认证类型从spring容器取出指定的bean
        AuthService passwordAuthservice = applicationContext.getBean("password_authservice", AuthService.class);

        // 调用统一的execute方法认证
        UserExt userExt = passwordAuthservice.execute(authParamsDto);

        // 封装userExt为userDetails
        UserDetails userPrincipal = getUserPrincipal(userExt);

        return  userPrincipal;

    }

    private UserDetails getUserPrincipal(UserExt userExt){

        // 权限
        String[] authorities = {"test"};

        // 将用户信息转成json
        String userJson = JSON.toJSONString(userExt);

        UserDetails userDetails = User.withUsername(userJson).password(userExt.getPassword()).authorities(authorities).build();

        return  userDetails;
    }
}
